package grape.workflow.rest.flowable.ui.task;

import org.flowable.ui.task.conf.Bootstrapper;
import org.flowable.ui.task.properties.FlowableTaskAppProperties;
import org.flowable.ui.task.service.runtime.FlowableAppDefinitionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * 重写 task ui conf 的bootstrap {@link Bootstrapper}
 * Created by yangwei
 * Created at 2020/6/8 17:39
 */
public class TaskBootstrapper implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger LOGGER = LoggerFactory.getLogger(TaskBootstrapper.class);

    @Autowired
    private FlowableAppDefinitionService appDefinitionService;

    @Autowired
    private FlowableTaskAppProperties taskAppProperties;

    private Boolean inited = false;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null || event.getApplicationContext().getParent().getParent() == null) { // Using Spring MVC, there are multiple child contexts. We only care about the root
            if (inited) {
                return;
            }
            if (taskAppProperties == null || taskAppProperties.isAppMigrationEnabled()) {
                String appMigrationResult = appDefinitionService.migrateAppDefinitions();
                LOGGER.info(appMigrationResult);
            }
            inited = true;
        }
    }
}
